package com.yitao.cms.service.product;

import com.querydsl.core.types.Order;
import com.querydsl.core.types.OrderSpecifier;
import com.skipper.base.bean.CommonStatus;
import com.skipper.base.bean.DataOutput;
import com.skipper.base.bean.PagedInput;
import com.skipper.base.bean.PagedOutput;
import com.skipper.base.data.querydsl.PredicateBuilder;
import com.skipper.base.service.GenericEntityService;
import com.yitao.client.constant.ProductConstant;
import com.yitao.client.dto.product.OperationProductCategoryDto;
import com.yitao.client.model.product.OperationProductCategoryModel;
import com.yitao.client.model.product.QOperationProductCategoryModel;
import com.yitao.cms.constant.UserErrorEnum;
import com.yitao.cms.constant.UserSession;
import com.yitao.cms.dto.productCategory.ProductCategoryDetailDto;
import com.yitao.cms.model.operationUser.OperationUserCmsModel;
import com.yitao.cms.utils.BaseUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Function:
 * Date: 2019/2/28
 *
 * @author skipper
 * @desc
 * @see
 */
@Service
public class OperationProductCategoryService extends GenericEntityService<OperationProductCategoryModel, OperationProductCategoryDto, QOperationProductCategoryModel> {

    public OperationProductCategoryService(EntityManager entityManager) {
        super(entityManager);
    }

    @Autowired
    private ProductCategoryRelationService productCategoryRelationService;
    private BaseUtils baseUtils = BaseUtils.getInstance();

    /**
     * 添加运营分类数据数据信息
     *
     * @param operationProductCategoryDto
     * @param request
     * @return
     */
    @Transactional
    public DataOutput updateProductCategory(OperationProductCategoryDto operationProductCategoryDto, HttpServletRequest request) {
        //获取登录信息
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) { // 未登录
            //用户登录时可注释掉
            return new DataOutput(UserErrorEnum.NULL_LOGIN.getCode(), UserErrorEnum.NULL_LOGIN.getDesc());
        }
        if (operationProductCategoryDto.getCategoryName() != null) {
            OperationProductCategoryModel operationProductCategoryModel = new OperationProductCategoryModel();
            if (operationProductCategoryDto.getCategoryType() == null) {
                operationProductCategoryDto.setCategoryType(ProductConstant.ProductCategoryTypeEnum.OPERATION_CATEGORY.getCode());
            }
            if (operationProductCategoryDto.getParentId() == null||operationProductCategoryDto.getParentId()==0L) {
                operationProductCategoryDto.setCategoryLevel(1);
                operationProductCategoryDto.setParentId(0L);
                operationProductCategoryDto.setCategoryLevel(1);
            }else{
                OperationProductCategoryModel  operationProductCategoryModel1=queryFactory.select(Q).from(Q).where(Q.id.eq(operationProductCategoryDto.getParentId())).fetchFirst();
                if (operationProductCategoryModel1!=null ){
                    if (operationProductCategoryModel1.getCategoryLevel()!=null && operationProductCategoryModel1.getCategoryLevel()!=0){
                        operationProductCategoryDto.setCategoryLevel(operationProductCategoryModel1.getCategoryLevel()+1);
                    }else{
                        return new DataOutput(CommonStatus.BAD_REQUEST.getCode(),"父级分类级别有误");
                    }
                }else{
                    return new DataOutput(CommonStatus.BAD_REQUEST.getCode(),"未查询到父级分类信息，请确认输入是否有误!");
                }
            }
            BeanUtils.copyProperties(operationProductCategoryDto, operationProductCategoryModel);
            //判断是否重名
            if (operationProductCategoryDto.getId() == null || operationProductCategoryDto.getId() == 0L) {//新增
                List<OperationProductCategoryModel> list =
                        repository.findAll(Q.categoryName.eq(operationProductCategoryDto.getCategoryName())
                                .and(Q.shopId.eq(userSession.getShopId()))
                                .and(Q.isDelete.eq(false)));
                if (list.size() > 0) {
                    return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "分类名称已存在，请重新输入!");
                }
                if (operationProductCategoryModel.getCategorySort() == null) {//默认排序值
                    operationProductCategoryModel.setCategorySort(1);
                }
                operationProductCategoryModel.setDelete(false);
                operationProductCategoryModel.setCreateBy(Long.valueOf(userSession.getId()));
                operationProductCategoryModel.setCreateTime(new Date());
            } else {//编辑
                OperationProductCategoryModel operationProductCategoryModel1 = repository.findOne(Q.id.eq(operationProductCategoryDto.getId()));
                operationProductCategoryModel.setCategoryCode(operationProductCategoryModel1.getCategoryCode());
                operationProductCategoryModel.setCategoryLevel(operationProductCategoryModel1.getCategoryLevel());
                operationProductCategoryModel.setCategoryType(operationProductCategoryModel1.getCategoryType());
                operationProductCategoryModel.setDelete(operationProductCategoryModel1.getDelete());
                operationProductCategoryModel.setCreateBy(operationProductCategoryModel1.getCreateBy());
                operationProductCategoryModel.setCreateTime(operationProductCategoryModel1.getCreateTime());
            }
            //补充shopid及登陆用户，创建时间等信息
            operationProductCategoryModel.setLastUpdateBy(Long.valueOf(userSession.getId()));
            operationProductCategoryModel.setLastUpdateTime(new Date());
            operationProductCategoryModel.setShopId(userSession.getShopId());
            OperationProductCategoryModel operationProductCategoryModel1 = repository.save(operationProductCategoryModel);
            if (operationProductCategoryModel1 != null) {
                if (operationProductCategoryDto.getProductIds() != null && operationProductCategoryDto.getProductIds().size() > 0) {
                    //插入关联产品表数据
                    return productCategoryRelationService.insertProductCategoryRelation(operationProductCategoryModel1.getId(), operationProductCategoryDto.getProductIds());
                }
                return new DataOutput(convertEntityToDto(operationProductCategoryModel1));
            } else {
                return new DataOutput(CommonStatus.SERVER_ERROR);
            }

        } else {
            return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "分类名称不能为空!");
        }

    }

    /**
     * 根据ID删除数据
     *
     * @param categoryId
     * @return
     */
    @Transactional
    public DataOutput deleteProductCategoryById(Long categoryId) {
        if (categoryId != null) {
            List<OperationProductCategoryModel> list = repository.findAll(Q.parentId.eq(categoryId).and(Q.isDelete.eq(false)));
            if (list != null && list.size() > 0) {
                return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "该运营分类下有子节点，请先删除子节点!");
            }
            //判断是否有关联商品
            List<Long> list1 = productCategoryRelationService.findProductIdsByCategoryId(categoryId);
            if (!CollectionUtils.isEmpty(list1)){
                return baseUtils.getBadErrorMsg("请先删除分类下的所有商品!");
            }
        }
        int result = repository.updateByWhere(Q.id.eq(categoryId),
                it -> it.set(Q.isDelete, true));
        if (result > 0) {
            return new DataOutput(CommonStatus.SUCCESS.getCode());
        } else {
            return new DataOutput(CommonStatus.SERVER_ERROR.getCode(), "删除失败，请重新操作!");
        }


    }

    /**
     * 根据运营分类Id查询运营分类信息
     *
     * @param categoryId
     * @return
     */
    public DataOutput findProductCategoryById(Long categoryId) {
        List<OperationProductCategoryModel> operationProductCategoryModels = repository.findAll(Q.id.eq(categoryId));
        ProductCategoryDetailDto productCategoryDetailDto = new ProductCategoryDetailDto();
        if (operationProductCategoryModels.size() > 0) {
            BeanUtils.copyProperties(operationProductCategoryModels.get(0), productCategoryDetailDto);
            //补充产品关联产品id
            productCategoryDetailDto.setProductIds(productCategoryRelationService.findProductIdsByCategoryId(categoryId));
            productCategoryDetailDto.setProductCodes(productCategoryRelationService.findProductCodesByCategoryId(categoryId));
        }
        return new DataOutput(productCategoryDetailDto);

    }

    /**
     * 根据运营分类Id查询运营分类信息
     *
     * @param categoryId
     * @return
     */
    public OperationProductCategoryModel findProductCategoryByCategoryId(Long categoryId) {
        if (categoryId != null) {
            return queryFactory.select(Q).from(Q).where(Q.id.eq(categoryId).and(Q.isDelete.eq(false))).fetchFirst();
        }
        return null;

    }


    /**
     * 返回运营分类递归列表
     *
     * @return
     */
    public DataOutput findProductCategoryList(HttpServletRequest request) {
        //验证登陆信息
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) {
            return new DataOutput(UserErrorEnum.NULL_LOGIN.getCode(), UserErrorEnum.NULL_LOGIN.getDesc());
        }
        try {
            List<OperationProductCategoryModel> productCategoryModelList = repository.findAll(Q.parentId.eq(0L)
                            .and(Q.isDelete.eq(false))
                            .and(Q.shopId.eq(userSession.getShopId()))
                            .and(Q.isDelete.eq(false))
                    , new OrderSpecifier<>(Order.DESC, Q.categorySort));
            return new DataOutput(getProductCategoryTreeList(productCategoryModelList, null, false));
        } catch (Exception e) {
            logger.info("获取产品运营分类列表失败{}!", e.getMessage());
            return new DataOutput(CommonStatus.SERVER_ERROR.getCode(), e.getMessage());
        }
    }
    //递归查询运营分类下级菜单

    public List<OperationProductCategoryDto> getProductCategoryTreeList(List<OperationProductCategoryModel> productCategoryModelList, List<Long> categoryIds, Boolean status) {
        List<OperationProductCategoryDto> operationProductCategoryDtos = new ArrayList<>();
        //循环父级添加子集
        for (OperationProductCategoryModel productCategoryModel : productCategoryModelList) {
            OperationProductCategoryDto operationProductCategoryDto = convertEntityToDto(productCategoryModel);
            //补充关联产品
            operationProductCategoryDto.setProductIds(productCategoryRelationService.findProductIdsByCategoryId(operationProductCategoryDto.getId()));
            operationProductCategoryDto.setProductCodes(productCategoryRelationService.findProductCodesByCategoryId(operationProductCategoryDto.getId()));
            operationProductCategoryDto.setChildren(
                    getProductCategoryTreeList(findProductCategoryByParentId(productCategoryModel.getId(), categoryIds, status), categoryIds, status));
            operationProductCategoryDtos.add(operationProductCategoryDto);
        }
        return operationProductCategoryDtos;
    }

    public List<OperationProductCategoryModel> findProductCategoryByParentId(Long parentId, List<Long> productCategoryIdList, Boolean status) {
        //获取菜单
        List<OperationProductCategoryModel> categoryModels = repository.findAll(Q.parentId.eq(parentId)
                .and(Q.isDelete.eq(status)), new OrderSpecifier<>(Order.DESC, Q.categorySort));
        if (productCategoryIdList == null) {
            return categoryModels;
        }
        List<OperationProductCategoryModel> operationProductCategoryModels = new ArrayList<>();
        for (OperationProductCategoryModel productCategoryModel : categoryModels) {
            convertEntityToDto(productCategoryModel);
            if (productCategoryIdList.contains(productCategoryModel.getId())) {
                operationProductCategoryModels.add(productCategoryModel);
            }
        }
        return operationProductCategoryModels;
    }


    public PagedOutput<OperationProductCategoryDto> findProductCategoryList(
            HttpServletRequest request,
            Integer categoryType, Integer categoryLevel, String categoryName, PagedInput pagedInput) {
        //验证登陆信息
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) {
            return new PagedOutput<>(pagedInput, 0, null);
        }
        PagedOutput<OperationProductCategoryModel> pagedOutput = repository.pagingList(PredicateBuilder.conjunction()
                        .ifNotNullThenAnd(categoryType, () -> Q.categoryType.eq(categoryType))
                        .ifNotNullThenAnd(categoryLevel, () -> Q.categoryLevel.eq(categoryLevel))
                        .ifHasTextThenAnd(categoryName, () -> Q.categoryName.like("%" + categoryName + "%"))
                        .ifNotNullThenAnd(userSession.getShopId(), () -> Q.shopId.eq(userSession.getShopId()))
                        .and(() -> Q.isDelete.eq(false)).get()
                , pagedInput, new OrderSpecifier<>(Order.DESC, Q.categorySort));

        List<OperationProductCategoryDto> categoryDtos = pagedOutput.getData().stream().map(it -> {
            OperationProductCategoryDto operationProductCategoryDto = new OperationProductCategoryDto();
            BeanUtils.copyProperties(it, operationProductCategoryDto);
            operationProductCategoryDto.setProductIds(productCategoryRelationService.findProductIdsByCategoryId(operationProductCategoryDto.getId()));
            operationProductCategoryDto.setProductCodes(productCategoryRelationService.findProductCodesByCategoryId(operationProductCategoryDto.getId()));
            return operationProductCategoryDto;
        }).collect(Collectors.toList());
        return new PagedOutput<>(pagedInput, pagedOutput.getTotalElements(), categoryDtos);
    }

    /**
     * 查询运营分类子集
     * @param request
     * @return
     */
    public DataOutput findProductCategorySubsetList(HttpServletRequest request){
        //验证登陆信息
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) {
            return new DataOutput(UserErrorEnum.NULL_LOGIN.getCode(), UserErrorEnum.NULL_LOGIN.getDesc());
        }
      List<OperationProductCategoryDto> list =  repository.findAll(Q.shopId.eq(userSession.getShopId()).and(Q.isDelete.eq(false)).and(Q.parentId.gt(0L)))
        .stream().map(this::convertEntityToDto).collect(Collectors.toList());
        return baseUtils.getSuccessMsg(list);
    }


}